package fun.ticsmyc.tmall.item.order.listener;

import com.fasterxml.jackson.databind.ObjectMapper;

import fun.ticsmyc.tmall.item.order.service.OrderService;
import fun.ticsmyc.tmall.item.pojo.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 消息队列监听器
 * @author Ticsmyc
 * @date 2020-08-19 10:04
 */
@Component
public class OrderListener {


    @Autowired
    private OrderService orderService;

    @Autowired
    private ObjectMapper mapper;

//    private AtomicInteger count= new AtomicInteger(0);

    private Logger logger = LoggerFactory.getLogger(OrderListener.class);

    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(value="ORDER.MODIFY.QUEUE",durable = "true"),
            exchange=@Exchange(value="ORDER.EXCHANGE",ignoreDeclarationExceptions = "true",type= ExchangeTypes.TOPIC),
            key={"order"}
    ))
    public void insertOrder(Map<String,String> msg){
        String method = msg.get("method");
        if("insert".equals(method)){
            Order order = null;
            try {
                order = mapper.readValue(msg.get("order"), Order.class);
            } catch (IOException e) {
                logger.error("反序列化失败:+"+msg.get("order"));
            }
            if(order != null){
                try{
                    //插入mysql
                    this.orderService.insertOrder(order);
                }catch(DuplicateKeyException e){
                    logger.warn("重复主键："+order.getId());
                }
                //删除redis
                this.orderService.deleteOrderInRedis(order.getId(),order.getUserId());
            }
        }
//        logger.info("插入"+count.getAndIncrement());
    }
}
